import SwiftUI
import PhotosUI
import CoreLocation
import CoreData
import Vision
import CoreML

struct ContentView: View {
    @StateObject var photoService = PhotoService()
    @State private var selectedTabIndex = 0
    @State private var showNewLocationAxis = false
    
    private let tabItems = [
        TabBarItem(icon: "mappin.and.ellipse", label: "地点"),
        TabBarItem(icon: "calendar", label: "时间"),
        TabBarItem(icon: "location", label: "附近"),
        TabBarItem(icon: "square.and.arrow.up", label: "社媒"),
        TabBarItem(icon: "testtube.2", label: "测试")
    ]
    
    var body: some View {
        Group {
            switch photoService.authorizationStatus {
            case .notDetermined:
                // 直接显示主界面，让iOS原生权限弹窗处理
                mainContentView
                
            case .denied, .restricted:
                // 权限被拒绝时显示主界面，但会提示用户
                mainContentView
                    .overlay(
                        VStack {
                            Spacer()
                            HStack {
                                Image(systemName: "exclamationmark.triangle.fill")
                                    .foregroundColor(.orange)
                                Text("请在设置中允许访问照片以使用完整功能")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                            .padding()
                            .background(Color(.systemBackground))
                            .cornerRadius(8)
                            .padding()
                        }
                    )
                
            case .authorized, .limited:
                // 显示主应用界面
                if photoService.isLoading && photoService.photos.isEmpty {
                    // 只在首次加载且没有照片时显示加载界面
                    PhotoProcessingView(photoService: photoService)
                } else {
                    // 显示主界面
                    mainContentView
                }
                
            @unknown default:
                // 未知状态，显示主界面
                mainContentView
            }
        }
        .onAppear {
            print("🟢 ContentView 出现 - 状态: \(photoService.authorizationStatus.rawValue), 照片: \(photoService.photos.count)张")
            
            // 检查持久化状态
            photoService.checkPersistenceStatus()
            
            // 🚀 修复：确保PhotoService初始化完成后再加载照片
            Task {
                // 等待一小段时间确保PhotoService初始化完成
                try? await Task.sleep(nanoseconds: 100_000_000) // 0.1秒
            
            // 如果权限未确定，自动触发iOS原生权限弹窗
            if photoService.authorizationStatus == .notDetermined {
                    await photoService.requestAuthorization()
            }
            
                // 🚀 修复：简化加载条件，只要权限允许就尝试加载
                if (photoService.authorizationStatus == .authorized || photoService.authorizationStatus == .limited) && photoService.photos.isEmpty {
                    print("🟢 开始加载照片...")
                    await photoService.loadAllPhotos()
                }
            }
        }
        .overlay(
            // 地理编码进度覆盖层 - 只在真正进行地理编码时显示
            Group {
                if photoService.isGeocodingInProgress && photoService.geocodingTotalPhotos > 0 {
                    Color.black.opacity(0.3)
                        .ignoresSafeArea()
                    
                    GeocodingProgressView(photoService: photoService)
                        .frame(maxWidth: 300)
                }
            }
        )
    }
    
    private var mainContentView: some View {
        ZStack {
            // 主内容区域
            VStack(spacing: 0) {
                // 页面内容
                TabView(selection: $selectedTabIndex) {
                    Group {
                        if showNewLocationAxis {
                            LocationAxisNewView()
                        } else {
                    LocationAxisView()
                        }
                    }
                        .tag(0)
                    
                    TimelineView(photoService: photoService)
                        .tag(1)
                    
                    NearbyView()
                        .tag(2)
                    
                    SocialMediaView()
                        .tag(3)
                    
                    TestView()
                        .tag(4)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                
                // 底部TabBar
                TabBar(selectedIndex: $selectedTabIndex, items: tabItems)
        }
        }
        .ignoresSafeArea(.keyboard)
        .environmentObject(photoService) // 🚀 修复：添加环境对象传递
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("ShowNewLocationAxis"))) { _ in
            print("📍 [ContentView] 收到显示新地点轴视图的通知")
            showNewLocationAxis = true
            selectedTabIndex = 0 // 切换到地点轴标签
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("ShowOldLocationAxis"))) { _ in
            print("📍 [ContentView] 收到返回旧地点轴视图的通知")
            showNewLocationAxis = false
        }
    }
}

#Preview {
    ContentView()
        .environmentObject(PhotoService())
} 
